import {
    AfterViewChecked,
    Component,
    ElementRef,
    EventEmitter,
    Injector,
    Output,
    ViewChild
} from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    MainTaskServiceProxy,
    MainTaskGoProductionDto,
    MaintenanceEditDto,
    ReceiveTaskInput,
    TaskDto,
    NameValueDtoOfNameValueDto,
    PipelineServiceProxy,
    PipelineNodesServiceProxy,
    OrganizationUnitServiceProxy,
    SideTaskServiceProxy
} from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
//import { IOrganizationUnitsTreeComponentData, OrganizationUnitsTreeComponent } from '../shared/organization-unit-tree.component';
//import { CreateOrdinaryFormComponent} from './create-ordinary-form/create-ordinary-form.component';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
//import { TaskService } from '../task/Task.service';
import * as moment from 'moment';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import { ComboboxItemDto } from '@shared/service-proxies/ztdevice-service-proxies';

@Component({
    selector: 'batchIntoProduceModal',
    templateUrl: './batch-into-produce.component.html'
    //styleUrls: ['./flowapplyordinarycreate.component.css']
})


export class BatchIntoProduceComponent extends AppComponentBase {
    // @ViewChild('createOrdinaryForm') createOrdinaryForm: CreateOrdinaryFormComponent;

    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('selectpaginator') selectpaginator: Paginator;
    @ViewChild('taskdataTable') taskdataTable: Table;
    @ViewChild('selectdataTable') selectdataTable: Table;
    selectPrimengTableHelper: PrimengTableHelper;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    filterText = '';
    active = false;
    saving = false;
    selected: any[];
    receiveTasks = new Array<ReceiveTaskInput>();
    dueDate = new Date();
    isReceived = true;
    isCompleted = false;
    order: TaskDto = new TaskDto();
    mainTaskGoProductionList = new Array<MainTaskGoProductionDto>();
    Outsourcings;
    cols: any[];
    tmpls: NameValueDtoOfNameValueDto[];
    tmplName = '';
    emptyText = '<<<<<选择管道模板>>>>>>';
    emptyText1 = '<<<<<选择主制班组>>>>>>';
    teamGroups: ComboboxItemDto[] = [];
    teamGroupName = '';
    type = 0;
    constructor(
        injector: Injector,

        private _mainTaskServiceProxy: MainTaskServiceProxy,
        private _pipelineService: PipelineServiceProxy,
        private _taskServiceProxy: PipelineNodesServiceProxy,
        private _organization: OrganizationUnitServiceProxy,
        private _sideTaskServiceProxy: SideTaskServiceProxy
    ) {
        super(injector);
        this.selectPrimengTableHelper = new PrimengTableHelper();
    }
    show(type: number): void {
        this.active = true;
        this.selected = [];
        this.type = type;
        this.selectPrimengTableHelper.records = this.selected;
        this.selectPrimengTableHelper.totalRecordsCount = 0;
        this._pipelineService.getPipelineTmpls().subscribe(result => {
            this.tmpls = result.items;
            console.log(this.dueDate);
        });
        this._organization.getTeamGroups().subscribe(result => {
            this.teamGroups = [];
            for (let i = 0; i < result.items.length; i++) {
                let teamGroup = new ComboboxItemDto();
                teamGroup.displayText = result.items[i].displayText;
                teamGroup.value = result.items[i].displayText;

                this.teamGroups.push(teamGroup);
            }

        this.modal.show();
    });
}
    deletePipe(pipe) {
        for (let i = 0; i < this.selected.length; i++) {
            if (this.selected[i].id === pipe.id) {
                this.selected.splice(i, 1);
            }
        }
    }
    save(): void {
        if ( this.type === 1 ) {
            for (let i = 0; i < this.selected.length; i++) {
                let MainTaskGoProduction = new MainTaskGoProductionDto();
                MainTaskGoProduction.mainTeamGroup = this.teamGroupName;
                MainTaskGoProduction.pipeTmplName = this.tmplName;
                MainTaskGoProduction.quantity = this.selected[i].totalQuantity;
                MainTaskGoProduction.comTime = this.selected[i].completionTime;
                MainTaskGoProduction.id = this.selected[i].id;
                this.mainTaskGoProductionList.push(MainTaskGoProduction);
            }
            let input = this.mainTaskGoProductionList;
            this.saving = true;
            this._mainTaskServiceProxy
                .batchProduction(input)
                .pipe(
                    finalize(() => {
                        this.saving = false;
                        this.mainTaskGoProductionList = [];
                    })
                )
                .subscribe(() => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.close();
                });
        } else if ( this.type === 2) {
            for (let i = 0; i < this.selected.length; i++) {
                let MainTaskGoProduction = new MainTaskGoProductionDto();
                MainTaskGoProduction.mainTeamGroup = this.teamGroupName;
                MainTaskGoProduction.pipeTmplName = this.tmplName;
                MainTaskGoProduction.quantity = this.selected[i].totalQuantity;
                MainTaskGoProduction.comTime = this.selected[i].completionTime;
                MainTaskGoProduction.id = this.selected[i].id;
                this.mainTaskGoProductionList.push(MainTaskGoProduction);
            }
            let input = this.mainTaskGoProductionList;
            this.saving = true;
            this._sideTaskServiceProxy
                .batchProduction(input)
                .pipe(
                    finalize(() => {
                        this.saving = false;
                        this.mainTaskGoProductionList = [];
                    })
                )
                .subscribe(() => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.close();
                });
        }

    }
    close(): void {
        this.active = false;
        this.primengTableHelper.records = null;
        this.filterText = '';
        this.selected = [];
        this.mainTaskGoProductionList = [];
        this.tmplName = '';
        this.teamGroupName = '';
        this.modal.hide();
    }
//获取主制任务列表
    getModels(event?: LazyLoadEvent, se?: number) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);

            return;
        }

        this.primengTableHelper.showLoadingIndicator();

        this._mainTaskServiceProxy
            .getMainTasks(
                this.filterText,
                this.isReceived,
                undefined,
                this.isCompleted,
                58,
                this.primengTableHelper.getSkipCount(this.paginator, event),
                this.primengTableHelper.getMaxResultCount(this.paginator, event)
            )
            .subscribe(result => {
                console.log(result);
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }
//获取定制任务列表
getMonths(event?: LazyLoadEvent, se?: number) {
    console.log(se);
    if (this.primengTableHelper.shouldResetPaging(event)) {
        this.paginator.changePage(0);
        return;
    }

    this.primengTableHelper.showLoadingIndicator();
    this._sideTaskServiceProxy
        .getSideTasks(
            this.filterText,
            this.isReceived,
            undefined,
            this.isCompleted,
            58,
            this.primengTableHelper.getSkipCount(this.paginator, event),
            this.primengTableHelper.getMaxResultCount(this.paginator, event)
        )
        .subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
}

    //加入要投产的任务
    joinTask(record) {
        //let dueDate = new Date();
        record.receptionTime = moment(this.dueDate);
        this.selected.push(record);
    }
    //获取要投产的任务列表
    getModels1() {
        this.selectPrimengTableHelper.records = this.selected;
        this.selectPrimengTableHelper.totalRecordsCount = this.selected.length;
        this.selectPrimengTableHelper.hideLoadingIndicator();
        this._taskServiceProxy
            .getTeamGroupName(this.primengTableHelper.records[0].id)
            .subscribe(result => {
                this.teamGroupName = result.groupName;
                this.teamGroups = result.groups;
            });
    }

    //批量接收
    batchReceiveTask() {
        this.receiveTasks = [];
        for (let i = 0; i < this.selected.length; i++) {
            let receiveTask = new ReceiveTaskInput();
            receiveTask.id = this.selected[i].id;
            this.receiveTasks.push(receiveTask);
        }

        this._mainTaskServiceProxy
            .batchReceiveTask(this.receiveTasks)
            .subscribe(() => {
                this.notify.success(this.l('SuccessfullyDeleted'));
                this.getModels();
                this.getModels1();
            });
    }
}
